package com.itheima.reggie.web;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {//菜品和口味的表现层
    @Autowired
    DishService dishService;

    @Autowired
    DishFlavorService dishFlavorService;

    @Autowired
    CategoryService categoryService;


//    public R<String> save (@RequestBody DishDto dishDto){
//        log.info(dishDto.toString());
//
//        dishService.save
//    }


    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name){
        log.info("page : {},{},{}",page,pageSize,name);

        //1.构建条件构造器和分页对象
        Page<Dish> dishPage = new Page<>(page,pageSize);
        //JSON接受的数据是字符串,需要改成Integer
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);//模糊查询是生效
        //StringUtils.isEmpty(name):非空判断,导的是import org.apache.commons.lang.StringUtils;
        //1.5 添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //2.查询
        dishService.page(dishPage,queryWrapper);

        //最终返回给前端的
        Page<DishDto> dishDtoPage = new Page<>();
        //dishDtoPage拷贝dishPage内除了records以外的所有数据
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");

        //用增强for循环获取records数据
        ArrayList<DishDto> dishDtoList = new ArrayList<>();
        for (Dish dish : dishPage.getRecords()) {//23条dish数据
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(dish, dishDto);
            //获取菜品分类表,查询当前菜品的分类名称
            Category category = categoryService.getById(dish.getCategoryId());
            //注入CategoryName
            dishDto.setCategoryName(category.getName());

            dishDtoList.add(dishDto);

        }
        //将处理完毕后的dishDto集合封装到page对象中返回
        dishDtoPage.setRecords(dishDtoList);
        return R.success(dishDtoPage);
    }

        @PostMapping//接收的是json数据,所以在前面加@RequestBody
        public R<String> save(@RequestBody DishDto dishDto){
            dishService.saveFlavor(dishDto);
            return R.success("新增菜品成功");
        }
        //根据id查询菜品信息和对应的口味信息
        @GetMapping("/{id}")
        public R<DishDto> getFlavor(@PathVariable Long id){
            DishDto dishDto = dishService.getByIdFlavor(id);
            return R.success(dishDto);
        }

        //修改菜品信息
        @PutMapping//接收的是json数据,所以在前面加@RequestBody
        public R<String> update(@RequestBody DishDto dishDto){
            dishService.updateFlavor(dishDto);
            return R.success("修改菜品成功");
        }

    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        log.info("ids:{}",ids);
        dishService.removeByIds(ids);
        return R.success("套餐数据删除成功");
    }


     // 菜品单个起售和批量起售
    // UPDATE dish SET status=? WHERE (id IN (?))
    @PostMapping("/status/{status}")
    public R<String> Status(@PathVariable Integer status, Long[] ids) {

        List<Long> list = Arrays.asList(ids);

        LambdaUpdateWrapper<Dish> objectLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        objectLambdaUpdateWrapper.set(Dish::getStatus, status).in(Dish::getId, list);
        dishService.update(objectLambdaUpdateWrapper);
        return R.success("状态修改成功");

    }


      /*
      根据条件查询对应的菜品数据   //套餐管理->添加套餐——>添加菜品
      移动端页面菜品显示
      @param dish
      @return
      */
    @GetMapping("/list")
    //通过Dish这个实体来接收参数。
    // @Cacheable(value = "dish",key = "#dish.getCategoryId() + '_' + #dish.getStatus()")
    public R<List<DishDto>> list(Dish dish) {

        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //不为空且id相等
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus, 1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }
}
